<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入组织名称" clearable size="small" prefix-icon="el-icon-search"
                    style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                   :filter-node-method="filterNode"
                   ref="tree" default-expand-all @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
          <el-form-item label="网关MAC" prop="gatewayMac">
            <el-input
              v-model="queryParams.gatewayMac"
              placeholder="请输入网关MAC"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="设备MAC" prop="deviceMac">
            <el-input
              v-model="queryParams.deviceMac"
              placeholder="请输入设备MAC"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="account">
            <el-input
              v-model="queryParams.account"
              placeholder="请输入手机号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="设备名称" prop="deviceName">
            <el-input
              v-model="queryParams.deviceName"
              placeholder="请输入设备名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['device:zigbee:query']"
            >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['device:zigbee:export']"
            >导出
            </el-button>
          </el-form-item>
        </el-form>

        <el-col>
          <el-table v-loading="loading" :data="deviceList" border @selection-change="handleSelectionChange">
            <!--            <el-table-column type="selection" width="55" align="center"/>-->
            <el-table-column label="主键" align="center" prop="id" v-if="false"/>
            <el-table-column label="手机号" align="center" prop="account" width="120"/>
            <el-table-column label="网关MAC" align="center" prop="gatewayMac" width="180px"
                             :show-overflow-tooltip="true"
            />
            <!--            <el-table-column label="网关名称" align="center" prop="gatewayName"/>-->
            <el-table-column label="设备MAC" align="center" prop="deviceMac" width="180px" :show-overflow-tooltip="true"/>
            <el-table-column label="设备名称" align="center" prop="deviceName" :show-overflow-tooltip="true"/>
            <el-table-column label="组织名称" align="center" prop="deptName" :show-overflow-tooltip="true"/>
            <!--            <el-table-column label="产品类型" align="center" prop="deviceType"/>-->
            <!--      <el-table-column label="开关" align="center" prop="switchState"/>-->
            <el-table-column label="上报时间" align="center" prop="switchTime" :show-overflow-tooltip="true" width="180px"/>

            <!-- <el-table-column label="用户手机号" align="center" prop="account" />-->


            <!--            <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" width="180px"/>-->


            <el-table-column label="操作" align="center" width="150">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-view"
                  type="text"
                  size="mini"
                  slot="reference"
                  @click="handleDetails(scope.row)" v-hasPermi="['device:zigbee:detail']"
                >详情
                </el-button>

                <el-button
                  type="text"
                  icon="el-icon-delete"
                  size="mini"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['device:zigbee:remove']"
                >删除
                </el-button>
              </template>
            </el-table-column>

          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-col>
    </el-row>
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-descriptions title="网关信息">
      </el-descriptions>
      <gatewayDetails :row="gatewayMac" :column-count="3"></gatewayDetails>
      <el-divider/>
      <el-descriptions title="设备信息" :column=3 contentClassName="my-content" labelClassName="my-label">
        <el-descriptions-item label="设备名称">{{ form.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="MAC地址">{{ form.deviceMac }}</el-descriptions-item>
        <el-descriptions-item label="设备类型">
          <template>
            {{ form.deviceType }}
          </template>
          <template>
            <el-tag type="success"> {{ form.defaultDeviceName }}</el-tag>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <template>
            <div v-html="fetchStatusHtml">
            </div>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ form.switchTime }}</el-descriptions-item>
        <el-descriptions-item label="在网状态">
          <template v-if="form.lwbz==='0'">
            <template v-if="form.onlineType!=='3'">
              <template v-if="form.diffTime > (form.onlineTime * 60)">
                <div class="myTagOffline">离线</div>
              </template>
              <template v-else>
                <div class="myTagOnline">在线</div>
              </template>
            </template>
          </template>
          <template v-else>
            <div class="myTagOffNet">离网</div>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="推送状态">
          <template v-if="form.pushType==='1'">
            <div class="myTagOpen">都推送</div>
          </template>
          <template v-else-if="form.pushType==='2'">
            <div class="myTagOpen">布防</div>
          </template>
          <template v-else-if="form.pushType==='3'">
            <div class="myTagOpen">撤防</div>
          </template>
          <template v-else-if="form.pushType==='3'">
            <div class="myTagOpen">不推送</div>
          </template>
          <template v-else>
            <div class="myTagClose">未知</div>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="联动类型">
          <template v-if="form.spreadingType==='02'">
            <div class="myTagOpen">可联动</div>
          </template>
          <template v-else>
            <div class="myTagClose">不可联动</div>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ form.modifyTime }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
  exportDevice,
  sendUrl
} from '@/api/system/device'
import { deptTreeSelect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import gatewayDetails from '@/views/components/gateway/details'
import { fetchStatus } from '@/api/system/device'

export default {
  name: 'Device',
  components: { Treeselect, gatewayDetails },
  data() {
    return {
      // 遮罩层
      loading: true,
      loading1: false,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: '',
      value: false,
      value1: undefined,
      deviceStatusTitle: '设备实时数据',
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gatewayMac: undefined,
        deviceMac: undefined,
        deviceName: undefined,
        deviceType: undefined,
        account: undefined,
        deptId: undefined
      },
      actions: [],
      deviceType: '',
      fetchStatusHtml: '',

      quac: {
        deviceId: undefined
      },
      gatewayMac: undefined,

      cmd: {
        //url:undefined
        deviceType: undefined,
        purpose: undefined,
        controlParam: undefined
      },
      // 表单参数
      form: {},
      deviceActionForm: {},
      deviceKey: [],
      deviceValue: [],
      // 表单校验
      rules: {}
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDictDataByType('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.msgname
    })
  },
  methods: {
    fetchStatus,
    /** 查询设备列表 */
    getList() {
      this.loading = true

      if (!this.queryParams.deptId) {
        // 取出当前用户的组织ID
        this.queryParams.deptId = this.$store.getters.deptId
      }

      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 改变开关状态 */
    change(row) {
      let pp = this
      this.value1 = !this.value
      this.loading1 = true

      //调用开关状态改变的接口  开始
      //alert(JSON.stringify(row))

      let controlState = ''
      if (this.value) {
        controlState = '1'
      } else {
        controlState = '2'
      }
      let wayNumber = ''
      if ((row.deviceType).indexOf('_') != -1) {
        wayNumber = (row.deviceType).charAt((row.deviceType).length - 1)
      }

      let waycmd = ''
      if (wayNumber != null && wayNumber != '') {
        waycmd = '"wayNumber":"' + wayNumber + '",'
      }

      let controlParam = '{"actions":{' + waycmd + '"controlState":"' + controlState + '","timeExpand":0},"deviceMac":"' + row.deviceMac + '","gatewayMac":"' + row.gatewayMac + '","controlType":"DIRECT_CONTROL"}'

      let deviceType1 = row.deviceType

      //let deviceType = 'deviceType='+  this.zh(deviceType1)
      let deviceType = this.zh(deviceType1)
      //let purpose ='&purpose=CONTROL'
      let purpose = 'CONTROL'
      //let overUrl = deviceType+'&controlParam='+encodeURIComponent(controlParam)+purpose;
      //let overUrl = deviceType+'&controlParam='+(controlParam)+purpose;

      //let url = "http://localhost:8080/api/command/cmdDeal?"+overUrl;

      //let url = "https://api.zyzncloud.com:8080/api/command/cmdDeal?"+overUrl;
      //let url = "http://101.37.148.179:8080/api/command/cmdDeal?"+overUrl;

      //调用开关状态改变的接口  结束

      pp.cmd.deviceType = deviceType
      pp.cmd.purpose = purpose
      pp.cmd.controlParam = controlParam
      //获取设备状态信息
      sendUrl(pp.cmd).then(response => {
        //alert(JSON.stringify(response))
        if (response.msg === '操作成功') {
          pp.msgSuccess('改变开关状态成功')
          this.loading1 = false
        } else if (response.msg === '操作失败') {

          pp.value = !pp.value
          pp.msgError('改变开关状态失败')
          this.loading1 = false
        } else if (response.msg === '没有权限，请联系管理员授权') {
          pp.value = !pp.value
          pp.msgError('改变开关状态失败')
          this.loading1 = false
        }

      }).then(err => {

        if (err.msg === '操作失败') {
          this.loading1 = false
          pp.value = !pp.value
          pp.msgError('改变开关状态失败')
        }

      })
    },

    zh(deviceType) {
      switch (deviceType) {
        case '0FAA0504':
          return 'YiLuLianKongMianBan_0FAA0504'
          break

        case '0FC80402':
          return 'JiLiangChaZuo_10A_0FC80402'
          break

        case '0FAA0502':
          return 'YiLuMianBan_0FAA0502'
          break

        case '0FAA0602':
          return 'ErLuMianBan_0FAA0602'
          break

        case '0FAA0702':
          return 'SanLuMianBan_0FAA0702'
          break

        case '0FAA0604':
          return 'ErLuLianKongMianBan_0FAA0604'
          break

        case '0FAA0704':
          return 'SanLuLianKongMianBan_0FAA0704'
          break

        case '0FAA0804':
          return 'SiLuLianKongMianBan_0FAA0804'
          break

        case '0FAB0602':
          return 'SiLuLianKongMianBan_0FAB0602'
          break

        case '0FAA0804':
          return 'SiLuLianKongMianBan_0FAA0804'
          break

        case '0FAA0804':
          return 'SiLuLianKongMianBan_0FAA0804'
          break

        default:
          return null
      }
    },

    //将数据拼接为json格式
    handleDetails(row) {

      this.reset()
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = row.deviceName + '详情'
        // this.actions = form.actions
        // this.deviceType = form.deviceType
        this.gatewayMac = row.gatewayMac
        this.fetchStatusHtml = fetchStatus(this.form.actions, this.form.deviceType)
        console.log('ccc' + this.fetchStatusHtml)
      })

    },
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮
    cancel1() {
      this.open1 = false
      this.reset()
    },
    cancel2() {
      this.open2 = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        homeId: undefined,
        gatewayId: undefined,
        roomId: undefined,
        zigbeeMac: undefined,
        odIndex: undefined,
        deviceType: undefined,
        productType: undefined,
        wifiMac: undefined,
        wifiIp: undefined,
        name: undefined,
        imgUrl: undefined,
        type: undefined,
        createTime: undefined,
        modifyTime: undefined,
        switchState: undefined,
        lwbz: undefined,
        switchTime: undefined,
        pushtype: undefined,
        spreadingType: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加设备'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改设备'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateDevice(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addDevice(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(`是否确认删除设备${row.deviceMac}(${row.deviceName})`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delDevice({ id: row.id })
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportDevice(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.selectedOrgCode = data.id
      this.queryParams.deptId = data.id
      this.getList()
    }
  }
}
</script>

